package net.osc.web;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 权限过滤器
 * 
 * @author <a href=mailto:peng.wu@foxmail.com>wu.peng</a> 2012-8-10
 * 
 */
public abstract class PermissionFilter implements Filter {
	private static final Log LOG = LogFactory.getLog(PermissionFilter.class);

	protected WebApplicationContext appContext;
	protected FilterConfig config;
	protected String loginUrl;
	protected String indexUrl;

	public void init(FilterConfig filterConfig) throws ServletException {
		LOG.debug("PermissionFilter init...");
		this.appContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig
				.getServletContext());
		this.config = filterConfig;
		this.loginUrl = config.getServletContext().getInitParameter("login_url");
		this.indexUrl = config.getServletContext().getInitParameter("index_url");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String reqUrl = req.getRequestURI();
		OnlineUser ou = OnlineUser.getOnlineUser(req);
		if (reqUrl.equals(loginUrl)) {// 已经登录直接转到首页
			if (ou != null) {
				res.sendRedirect(indexUrl);
				return;
			}
		}
		// 收集系统管理的所有链接
		Set<String> allURLs = getAllURLs();
		allURLs.add(indexUrl);
		if (allURLs.contains(reqUrl)) {
			if (ou == null) {
				res.sendRedirect(loginUrl);
				return;
			} else {
				Set<String> userURLs = getUserURLs(ou.getUserCode());
				userURLs.add(indexUrl);
				if (!userURLs.contains(reqUrl)) {
					res.sendError(404);
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}

	public void destroy() {
		LOG.debug("PermissionFilter destroy...");
	}

	public abstract Set<String> getUserURLs(String userCode);

	public abstract Set<String> getAllURLs();

}
